<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加角色 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoleDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolelist" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template #default="scope">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 通过 for 循环 嵌套渲染二级权限 -->
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>

        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="showeditRightDialog(scope.row.id)">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="showdelRightDialog(scope.row)"
            >删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showSetRightDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="30%"
      @close="setRightDialogClosed"
    >
      <!-- 树形结构 -->
      <el-tree
        :data="rightslist"
        :default-checked-keys="defKeys"
        show-checkbox
        default-expand-all
        node-key="id"
        :props="treeProps"
        ref="treeRef"
      ></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色功能弹框 -->
    <el-dialog
      title="添加角色"
      @close="addrolesDialogClosed"
      :visible.sync="addRoleDialogVisible"
      width="50%"
    >
      <el-form
        :model="addFolesForm"
        :rules="addrolesRules"
        ref="addruleFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addFolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addFolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- //编辑角色信息对话框 -->
     <el-dialog
      title="修改角色"
      @close="editrolesDialogClosed"
      :visible.sync="editRoleDialogVisible"
      width="50%"
    >
      <el-form
        :model="editFolesForm"
        :rules="editrolesRules"
        ref="editruleFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editFolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editFolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      rolelist: [],
      // 控制分配权限对话框的显示与隐藏
      setRightDialogVisible: false,
      // 所有权限的数据
      rightslist: [],
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      //当前分配角色的id
      roleId: '',
      //当前角色的所有权限
      defKeys: [],
      addFolesForm: {
        roleName: '',
        roleDesc: ''
      },
      //表单规则
      addrolesRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '角色名的长度在3~10个字符之间',
            trigger: 'blur'
          }
        ],
        roleDesc:[
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 3,
            max: 20,
            message: '角色描述名的长度在3~20个字符之间',
            trigger: 'blur'
          }
        ]
      },
      //设置添加角色的显示与隐藏
      addRoleDialogVisible: false,
      //设置修改角色的显示与隐藏
      editRoleDialogVisible:false,
      //修改用户
      editFolesForm:{},
      //修改表单规则
       editrolesRules:{
          roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '角色名的长度在3~10个字符之间',
            trigger: 'blur'
          }
        ],
        roleDesc:[
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 3,
            max: 20,
            message: '角色描述名的长度在3~20个字符之间',
            trigger: 'blur'
          }
        ]
       }
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取所有角色的列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')

      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }

      this.rolelist = res.data

      //console.log(this.rolelist)
    },
    //删除用户权限功能
    async removeRightById(role, rightId) {
      //console.log(role, rightId)
      // 弹框提示用户是否要删除
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      //console.log(confirmResult); cancel 取消
      if (confirmResult == 'cancel') return this.$message.info('取消了删除！')
      //用户确定删除
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      //console.log(res);
      if (res.meta.status !== 200)
        return this.$message.error('删除用户权限失败！')
      //直接将服务器返回的权限数据赋值给该用户的权限数据 不需要重新渲染页面数据 用户体验更好
      role.children = res.data
    },
    //分配用户权限
    async showSetRightDialog(role) {
      this.roleId = role.id
      // 获取所有权限的数据
      const { data: res } = await this.$http.get('rights/tree')

      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败！')
      }

      // 把获取到的权限数据保存到 data 中
      this.rightslist = res.data
      //console.log(this.rightslist)
      this.getLeafKeys(role)

      this.setRightDialogVisible = true
    },
    // 通过递归的形式，获取角色下所有三级权限的id，并保存到 defKeys 数组中
    getLeafKeys(node) {
      // 如果当前 node 节点不包含 children 属性，则是三级节点
      //console.log(this.defKeys);
      if (!node.children) {
        return this.defKeys.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item)
      })
    },
    // 监听分配权限对话框的关闭事件
    setRightDialogClosed() {
      this.defKeys = []
    },
    // 提交修改权限表单
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getHalfCheckedKeys(), //半选节点组成的数组
        ...this.$refs.treeRef.getCheckedKeys() //全选节点组成的数组
      ]
      //console.log(keys);
      const idStr = keys.join(',') //将数组以逗号分隔转为字符串
      //console.log(this.roleId);

      //console.log(idStr);
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
      //console.log(res);
      if (res.meta.status !== 200) return this.$message.error('添加权限失败')
      this.$message.success('分配权限成功！')
      this.getRolesList()
      this.setRightDialogVisible = false
    },
    //删除用户角色功能
    async showdelRightDialog(role) {
      //console.log(role);
      // 弹框提示用户是否要删除
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // console.log(confirmResult); cancel  取消删除
      if (confirmResult == 'cancel') return this.$message.info('取消了删除！')
      //用户确定删除
      const { data: res } = await this.$http.delete('roles/' + role.id)
      //console.log(res);
      if (res.meta.status !== 200) return this.$message.error('删除角色失败')
      this.$message.success('删除角色成功！')
      //重新渲染
      this.getRolesList()
    },
    //提交角色信息
     addRoles() {
     // console.log(this.addFolesForm);
       this.$refs.addruleFormRef.validate(async vild=>{
        // console.log(vild); 验证不通过 返回 false 
         if(!vild) return this.$message.error('请输入合法的信息')
         //通过验证
          const {data:res} = await this.$http.post('roles',this.addFolesForm)
          //console.log(res);
          if(res.meta.status !== 201) return this.$message.error('添加角色失败') 
          //添加角色成功
              this.addRoleDialogVisible = false  //关闭对话框
            this.$message.success('添加角色成功！')
              //重新渲染
            this.getRolesList()
       })
      
    },
    //监听添加角色对话框关闭事件
    addrolesDialogClosed() {
      this.$refs.addruleFormRef.resetFields()
    },
    editrolesDialogClosed(){
      this.$refs.editruleFormRef.resetFields()
    },
    // 编辑提交角色
    editRoles(){
       this.$refs.editruleFormRef.validate(async vild=>{
         //console.log(vild); false验证不通过
         if(!vild) return this.$message.error('请输入合法的信息')
         //验证通过
        const {data:res}  = await this.$http.put('roles/'+this.editFolesForm.roleId,this.editFolesForm)
              //console.log(res);
          if(res.meta.status !== 200) return this.$message.error('修改角色失败') 

            this.$message.success('修改角色成功！') 
              //重新渲染
            this.getRolesList()
            this.editRoleDialogVisible = false 
       })
    },
    //显示修改弹出框事件
    async showeditRightDialog(id){
        //console.log(id);
        //根据id查询数据
          const {data:res} = await this.$http.get('roles/'+id)
          //console.log(res);
          if(res.meta.status !== 200) return this.$message.info('获取角色信息失败！')
          //将服务器返回的数据赋值给editFolesForm
          this.editFolesForm = res.data
          //console.log(res.data.roleId);//角色id
         // this.editRoles(res.data.roleId)
          
          //this.editRoles(res.data.id)
        this.editRoleDialogVisible = true 
    }
  }
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>